package com.lky.marshallmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lky.common.utils.PageUtils;
import com.lky.common.utils.Query;
import com.lky.common.utils.R;
import com.lky.common.vo.MemberVo;
import com.lky.marshallmall.order.constant.OrderConstant;
import com.lky.marshallmall.order.constant.OrderStatusEnum;
import com.lky.marshallmall.order.dao.OrderDao;
import com.lky.marshallmall.order.dao.OrderItemDao;
import com.lky.marshallmall.order.entity.OrderEntity;
import com.lky.marshallmall.order.entity.OrderItemEntity;
import com.lky.marshallmall.order.feign.CartFeignService;
import com.lky.marshallmall.order.feign.MemberFeignService;
import com.lky.marshallmall.order.feign.ProductFeignService;
import com.lky.marshallmall.order.feign.WmsFeignService;
import com.lky.marshallmall.order.interceptor.LoginUserInterceptor;
import com.lky.marshallmall.order.service.OrderItemService;
import com.lky.marshallmall.order.service.OrderService;
import com.lky.marshallmall.order.to.OrderCreateTo;
import com.lky.marshallmall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    OrderItemDao orderItemDao;
    @Autowired
    RabbitTemplate rabbitTemplate;


    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> getAddress = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberVo.getId());
            orderConfirmVo.setMemberAddress(address);
        },executor);

        CompletableFuture<Void> getCartItem = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //购物车数据
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(currentUserCartItems);
        },executor).thenRunAsync(()->{
            //查询库存信息
            List<OrderItemVo> itmes = orderConfirmVo.getItems();
            List<Long> skuIds = itmes.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIds);
            List<SkuHashStockVo> data = (List<SkuHashStockVo>) skuHasStock.getData(new TypeReference<List<SkuHashStockVo>>() {});
            if (data!=null){
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHashStockVo::getSkuId, SkuHashStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        },executor);

        CompletableFuture<Void> getIntegration = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //优惠券 （积分）
            Integer integration = memberVo.getIntegration();
            orderConfirmVo.setIntegration(integration);
        }, executor);

        //防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);


        CompletableFuture.allOf(getAddress,getCartItem,getIntegration).get();

        return orderConfirmVo;
    }


//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0);
        submitVoThreadLocal.set(vo);
        //下单，创建订单，验令牌，验价格，锁库存
        //验证令牌[令牌的对比和删除必须保证原子性]
        //返回的是0 和 1，如果存在就删除成功返回1，0代表校验失败
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), orderToken);
        if (0L == result){
            //失败  订单令牌校验失败 ： 1
            response.setCode(1);
            return response;
        }
        //验证成功：下单
        //1.创建订单
        OrderCreateTo order = createOrder();
        //验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = order.getPayPrice();
        if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01) {
            //金额对比成功
            //保存订单数据
            saveOrder(order);
            //锁定库存,只要有异常回归订单数据
            WareSkuLockVo lockVo = new WareSkuLockVo();
            lockVo.setOrderSn(order.getOrder().getOrderSn());
            List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                OrderItemVo itemVo = new OrderItemVo();
                itemVo.setSkuId(item.getSkuId());
                itemVo.setCount(item.getSkuQuantity());
                return itemVo;
            }).collect(Collectors.toList());
            lockVo.setLocks(orderItemVos);
            //远程锁库存
            R r = wmsFeignService.orderLockStock(lockVo);
//            int i = 10/0;
            if (r.getCode() == 0){
                // 成功
                //发送消息给mq
                rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                response.setOrder(order.getOrder());
                return response;
            }else {
                //锁定库存失败：3
                response.setCode(3);
                return response;
            }
        }else {
            //验价失败：2
            response.setCode(2);
            return response;
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity ordersn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return ordersn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())){
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
        }
    }

    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        orderDao.insert(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemDao.insert(orderItems.get(0));
//        orderItemService.saveOrUpdateBatch(orderItems);
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1.生成订单号0
        String timeId = IdWorker.getTimeId();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(timeId);

        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        entity.setMemberId(memberVo.getId());

        //获取收获地址信息
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        String address = memberFeignService.getAddress1(orderSubmitVo.getAddrId());
        entity.setReceiverDetailAddress(address);
        //订单状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setConfirmStatus(7);

        //获取所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(timeId);

        //验价
        computePrice(entity,orderItemEntities);
        orderCreateTo.setOrder(entity);
        orderCreateTo.setOrderItems(orderItemEntities);
        orderCreateTo.setPayPrice(entity.getPayAmount());

        return orderCreateTo;
    }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal coupon = BigDecimal.ZERO;
        BigDecimal integration = BigDecimal.ZERO;
        BigDecimal promotion = BigDecimal.ZERO;
        BigDecimal giftGrowthBegin = BigDecimal.ZERO;
        BigDecimal giftIntegrationBegin = BigDecimal.ZERO;
        //1.订单价格相关  订单总额叠加
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            BigDecimal realAmount = orderItemEntity.getRealAmount();
            total = total.add(realAmount);
            BigDecimal couponAmount = orderItemEntity.getCouponAmount();
            coupon = coupon.add(couponAmount);
            BigDecimal integrationAmount = orderItemEntity.getIntegrationAmount();
            integration = integration.add(integrationAmount);
            BigDecimal promotionAmount = orderItemEntity.getPromotionAmount();
            promotion = promotion.add(promotionAmount);
            Integer giftGrowth = orderItemEntity.getGiftGrowth();
            giftGrowthBegin = giftGrowthBegin.add(BigDecimal.valueOf(giftGrowth));
            Integer giftIntegration = orderItemEntity.getGiftIntegration();
            giftIntegrationBegin = giftIntegrationBegin.add(BigDecimal.valueOf(giftIntegration));
        }
        entity.setTotalAmount(total);
        //设置应付总额
        entity.setPayAmount(total.add(entity.getTotalAmount()));
        entity.setPromotionAmount(promotion);
        entity.setIntegrationAmount(integration);
        entity.setCouponAmount(coupon);
        entity.setGrowth(giftGrowthBegin.intValue());
        entity.setIntegration(giftIntegrationBegin.intValue());
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems!=null&currentUserCartItems.size()>0){
            List<OrderItemEntity> entities = currentUserCartItems.stream().map(carItem -> {
                OrderItemEntity orderItem = buildOrderItem(carItem);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return entities;
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo carItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1.订单信息，订单号

        //2.商品spu信息
        Long skuId = carItem.getSkuId();
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = (SpuInfoVo) spuInfoBySkuId.getData(new TypeReference<SpuInfoVo>() {});
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());

        //3.商品sku信息
        orderItemEntity.setSkuId(carItem.getSkuId());
        orderItemEntity.setSkuName(carItem.getTitle());
        orderItemEntity.setSkuPic(carItem.getImage());
        String skuAttr = StringUtils.collectionToDelimitedString(carItem.getSkuAttr(),"；");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(carItem.getCount());
        //5.积分信息
        orderItemEntity.setGiftGrowth(carItem.getPrice().intValue());
        orderItemEntity.setGiftIntegration(carItem.getPrice().intValue());
        //6.订单价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setSkuPrice(carItem.getPrice());
        //订单原始金额
        BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //订单实际金额
        BigDecimal real = orign.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount()).subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(real);


        return orderItemEntity;
    }

}